package com.appapi.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 该控制器中包含一点停开放平台上行接口和下行接口的相关示例代码，请参考。
 * 工具类使用：http://www.hutool.cn/ 中的 hutool-core hutool-crypto hutool-http 开发者可自行选用其他工具类
 */
@RestController
@RequestMapping("/api/zhtc")
public class TozhtcController {
    private Logger logger = LoggerFactory.getLogger(TozhtcController.class);
    private String key1 = "3nf1zz";
    private String secret1 = "g0qdly2cw9obvs82ywzxsv5pmmsrz72a";
    private String url2 = "https://openapi-test.yidianting.xin/openydt/api/v2/";
    private String url3 = "https://openapi-test.yidianting.xin/openydt/api/v3/";
    @Autowired
    private HttpServletRequest request;

    @RequestMapping("/greeting")
    public String greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
        logger.info("======================测试hello world=======================");
        return "Hello "+name;
    }

    @RequestMapping("/upward/v3")
    @ResponseBody
    public String upwardV2test3(@RequestBody(required = false) String data) {
        logger.info("data:{}", data);
        JSONObject obj = JSONObject.parseObject(data);
        JSONObject biz_content = obj.getJSONObject("biz_content");
        String sign = biz_content.getString("sign");
        String recordId = "20190924000022";
        String prePayKey = "keyZz2CV81lfNeG1I0wq";
        String s = prePayKey + ":" + recordId;
        String rsign = DigestUtil.md5Hex(s).toLowerCase();
        logger.info("sign:{},rsign:{}", sign, rsign);

        String resp = getCommonResponsePayUrl(true);
        return resp;
    }

    /**
     * 一点停开放平台平台主动上报类接口 对接
     *
     * @param cmd
     * @param data
     * @return
     */
    @RequestMapping("/upward/v2/xx/{cmd}")
    @ResponseBody
    public String upwardV2test2(@PathVariable String cmd, @RequestBody(required = false) String data) {
        String sign = request.getParameter("sign");
        String authorization = request.getHeader("Authorization");
        logger.info("api upward v2:Authorization={},cmd={},sign={},data={}", new Object[]{authorization, cmd, sign, data});
        String decodeAuthorization = new String(Base64.decode(authorization));
        logger.info("api upward v2:authorization={},decode:{}", new Object[]{authorization, decodeAuthorization});
        String[] authArray = decodeAuthorization.split(":");
        String signStr = authArray[0] + ":" + authArray[1] + ":" + "123456";
        String rsign = SecureUtil.md5(signStr).toLowerCase();
        logger.info("api upward v2:sign={},rsign:{}", new Object[]{sign, rsign});
        String resp = getCommonResponse(true);
        logger.info("api upward v2:请求值:{}--返回值:{}", new String[]{authorization, cmd, sign, data}, JSONObject.toJSONString(resp));
        return resp;
    }
    /*
     *    调用智慧平台第三方版本2接口
     * @Author gongchengbing
     * @Date  2020/7/20 0020 17:39
     * @Param [cmd, params]
     * @return java.lang.String
    */
    @RequestMapping("/tozhtc/v2/{cmd}")
    @ResponseBody
    public  String tozhtc2(@PathVariable String cmd,@RequestBody String params) {
        String date = DateUtil.format(new Date(), "yyyyMMddHHmmss");
        String sign = SecureUtil.md5(key1 + ":" + date + ":" + secret1);
        sign = sign.toLowerCase();
        String auth = Base64.encode(key1 + ":" + date);
        String resultStr =
                HttpRequest.post(url2 + cmd + "?sign=" + sign)
                        .header("Accept", "application/json")
                        .header("Content-Type", "application/json;charset=utf-8")
                        .header("Authorization", auth)
                        .body(params)
                        .execute().body();
        System.out.println("resultStr: " + resultStr);

        return resultStr;
    }

    /*
     *    调用智慧平台第三方版本2接口
     * @Author gongchengbing
     * @Date  2020/7/20 0020 17:39
     * @Param [cmd, params]
     * @return java.lang.String
     */
    @RequestMapping("/tozhtc/v3/{cmd}")
    @ResponseBody
    public  String tozhtc3(@PathVariable String cmd,@RequestBody String params) {
        String date = DateUtil.format(new Date(), "yyyyMMddHHmmss");
        String sign = SecureUtil.md5(key1 + ":" + date + ":" + secret1);
        sign = sign.toLowerCase();
        String auth = Base64.encode(key1 + ":" + date);
        String resultStr =
                HttpRequest.post(url3 + cmd + "?sign=" + sign)
                        .header("Accept", "application/json")
                        .header("Content-Type", "application/json;charset=utf-8")
                        .header("Authorization", auth)
                        .body(params)
                        .execute().body();
        System.out.println("resultStr: " + resultStr);

        return resultStr;
    }

    /**
     * 一点停开放平台下行接口调用 方法1：请求为map
     *
     * @param url    下行接口地址
     * @param key    授权标识
     * @param secret 授权秘钥
     * @param cmd    下行接口签名
     * @param params 参数
     * @return 返回为字符串
     */
    public static String downHandler1(String url, String key, String secret, String cmd, Map<String, Object> params) {

        String date = DateUtil.format(new Date(), "yyyyMMddHHmmss");
        String sign = SecureUtil.md5(key + ":" + date + ":" + secret);
        sign = sign.toLowerCase();
        String auth = Base64.encode(key + ":" + date);
        String resultStr =
                HttpRequest.post(url + cmd + "?sign=" + sign)
                        .header("Accept", "application/json")
                        .header("Content-Type", "application/json;charset=utf-8")
                        .header("Authorization", auth)
                        .body(JSONObject.toJSONString(params))
                        .execute().body();
        System.out.println("resultStr: " + resultStr);

        return resultStr;
    }

    /**
     * 一点停开放平台下行接口调用 方法2：请求和返回均为json字符串 纯json处理
     *
     * @param url     下行接口地址
     * @param key     授权标识
     * @param secret  授权秘钥
     * @param cmd     下行接口签名
     * @param jsonStr 参数
     * @return 返回为字符串
     */
    public static String downHandler2(String url, String key, String secret, String cmd, String jsonStr) {
        String date = DateUtil.format(new Date(), "yyyyMMddHHmmss");
        String sign = SecureUtil.md5(key + ":" + date + ":" + secret);
        sign = sign.toLowerCase();
        String auth = Base64.encode(key + ":" + date);
        String resultStr =
                HttpRequest.post(url + cmd + "?sign=" + sign)
                        .header("Accept", "application/json")
                        .header("Content-Type", "application/json;charset=utf-8")
                        .header("Authorization", auth)
                        .body(jsonStr)
                        .execute().body();
        System.out.println("resultStr: " + resultStr);

        return resultStr;
    }

    public static String getCommonResponse(Boolean success) {
        Map<String, Object> params = new HashMap<>();
        params.put("status", 1);
        params.put("message", "业务成功");

        if (success) {
            params.put("resultCode", 0);
        } else {
            params.put("resultCode", -1);
            params.put("data", new JSONObject());
        }

        return JSONObject.toJSONString(params);
    }

    public static String getCommonResponsePayUrl(Boolean success) {
        Map<String, Object> params = new HashMap<>();

        Date now = new Date();
        String nowStr = DateUtil.format(now, "yyyyMMddHHmmss");
        params.put("command", "REPORT_PAY_NOTICE_RETURN");
        params.put("message_id", "11111111111");
        params.put("sign_type", "MD5");
        params.put("sign", "");
        params.put("charset", "UTF-8");
        params.put("timestamp", nowStr);
        Map<String, Object> map = new HashMap<>();
        if (success) {
            map.put("code", 0);
            map.put("msg", "缴费成功");
            params.put("biz_content", map);
        } else {
            map.put("code", 1);
            map.put("msg", "缴费失败");
            params.put("biz_content", map);
        }

        return JSONObject.toJSONString(params);
    }

    public static void main(String[] args) {
        //授权标识
        String key = "3nf1zz";
        //授权秘钥
        String secret = "g0qdly2cw9obvs82ywzxsv5pmmsrz72a";
        //一点停开放平台下行接口调用地址
        String url = "https://openapi-test.yidianting.xin/openydt/api/v2/";
        //接口签名
        String cmd = "getParkInfo";
        //请求参数
        Map<String, Object> params = new HashMap<>();
        params.put("parkCode", "2KPI5T73");
        //https(http) POST 请求
        System.out.println("===================第一种请求方法=================");
        String resp2 = new TozhtcController().tozhtc2(cmd, JSON.toJSONString(params));
        System.out.println(resp2);

        System.out.println("===================第二请求种方法=================");
        String resp3 = downHandler2(url, key, secret, cmd, "{" +
                "\"parkCode\": \"2KPI5T73\"" + "}");
        System.out.println(resp3);
    }
}
